package cn.magictodo.weblog.web.service.impl;

import cn.magictodo.weblog.common.domain.dos.IpDo;
import cn.magictodo.weblog.common.domain.mapper.IpMapper;
import cn.magictodo.weblog.common.utils.Response;
import cn.magictodo.weblog.web.event.AddIpEvent;
import cn.magictodo.weblog.web.model.vo.ip.AddIpReqVO;
import cn.magictodo.weblog.web.service.IpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 前端传过来的ip地址
 *
 * @author liu
 * @since 2024-03-25 16:22
 */
@Service
public class IpServiceImpl implements IpService {
    @Autowired
    private IpMapper ipMapper;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public Response addIp(AddIpReqVO addIpReqVO) {
//        初始化
        LocalDate now = LocalDate.now();
        IpDo ipDo = ipMapper.selectByIpWithDate(addIpReqVO.getIp(), now);
        if (ipDo == null) {
            IpDo build = IpDo.builder()
                    .ip(addIpReqVO.getIp())
                    .country(addIpReqVO.getCountry())
                    .province(addIpReqVO.getProvince())
                    .city(addIpReqVO.getCity())
                    .isp(addIpReqVO.getIsp())
                    .createTime(LocalDateTime.now())
                    .updateTime(LocalDateTime.now())
                    .area(addIpReqVO.getArea())
                    .visitView(1L)
                    .net(addIpReqVO.getNet())
                    .build();
            ipMapper.insert(build);
            applicationEventPublisher.publishEvent(new AddIpEvent(this, build.getId()));
        }else {
            applicationEventPublisher.publishEvent(new AddIpEvent(this, ipDo.getId()));
        }


        return Response.success();
    }


}
